import { Context, HttpError, Next } from 'koa';

import { EasyKoaException } from '../error.ts';
import { NodeRequestException } from '../service/requestException.ts';
import { RESPONSE_MAP } from '../service/response.ts';
import { NodeResponseException } from '../service/responseException.ts';
import type { ResponseCode } from '../types';

export const errorHandler = async (ctx: Context, next: Next) => {
  try {
    await next();
  } catch (err: any) {
    console.warn(err);
    // logger.error(err);
    if (err instanceof EasyKoaException) {
      ctx.status = err.code;
      ctx.body = {
        code: err.code,
        message: err.message,
        success: false,
      };
    } else if (err instanceof HttpError) {
      ctx.status = err.status;
      ctx.body = {
        code: err.status,
        message: ctx.msg || err.message || RESPONSE_MAP[err.status as ResponseCode],
        success: false,
      };
    } else if (err instanceof NodeResponseException) {
      ctx.status = 500;
      ctx.body = {
        code: 500,
        message: `服务器内部错误：${err.message}`,
        success: false,
        result: err.source,
      };
    } else if (err instanceof NodeRequestException) {
      ctx.status = 500;
      ctx.body = {
        code: 500,
        message: `服务器请求外部服务时发生错误：${err.message}`,
        success: false,
      };
    } else if (err instanceof Error) {
      ctx.status = ctx.code || 500;
      ctx.body = {
        code: ctx.status,
        message: err.message,
        success: false,
      };
    } else {
      ctx.body = {
        code: 500,
        message: '服务器内部错误！！！',
        success: false,
        result: err,
      };
    }
  }
};
